package edu.sjsu.cs.queryopt.dbms.dao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;

import edu.sjsu.cs.queryopt.dbms.error.CommandException;
import edu.sjsu.cs.queryopt.dbms.main.DBMS;

public class Index {

	public String name;  //name of file

	public ArrayList<String> definitions;//1A 2A
	public int rowCount;
	public ArrayList<IndexRow> rows;

	public Index() {
		definitions = new ArrayList<String>();
		rowCount = 0;
		rows = new ArrayList<IndexRow>();
	}

	private class IndexRow {
		public int rid;
		public String keyString;

		public IndexRow(int rid, String keyString) {
			this.rid = rid;
			this.keyString = keyString;
		}
	}

	/**
	 * Adds the given row's values to rows list.
	 * @param rid
	 * @param keyString
	 */
	// adding the row !!! call from saveFile 
	public void addRow(int rid, String keyString) {
		rows.add(new IndexRow(rid, keyString));
	}

	/**
	 * Saves this index to a file called '<Index Name>.idx'.
	 * 
	 * @throws FileNotFoundException
	 */
	public void saveIndex() throws FileNotFoundException {
		System.out.println("\n\nSaving Index " + this.name + "...\n");

		PrintStream originalOut = System.out;

		System.setOut(new PrintStream(new File(this.name + ".idx")));

		for (String definition : definitions) {
			System.out.print(definition + " ");
		}

		System.out.println();
		System.out.println(rowCount);

		for (IndexRow row : rows) {
			System.out.println(row.rid + " '" + row.keyString + "' ");
		}

		System.out.close();
		System.setOut(originalOut);

		// Print output to System.out if DBMS.file flag is set.
		if (DBMS.file) {
			for (String definition : definitions) {
				System.out.print(definition + " ");
			}

			System.out.println();
			System.out.println(rowCount);

			for (IndexRow row : rows) {
				System.out.println(row.rid + " '" + row.keyString + "' ");
			}
		}
	}

	/**
	 * Loads '<Index Name>.idx' to this.index
	 * Prereq - this.name must be a valid index name
	 * @throws FileNotFoundException
	 * @throws CommandException 
	 */
	public void readIndex() throws FileNotFoundException, CommandException {
		Scanner in = new Scanner(new File(name + ".idx"));


		if (in.hasNextLine()) {
			String[] definitions = in.nextLine().split(" ");
			for (String definition : definitions)
				this.definitions.add(definition);
		} else {
			throw new CommandException("Invalid index file format.");
		}
		System.out.println("definitions " + definitions);
		if (in.hasNextLine()) {
			rowCount = Integer.parseInt(in.nextLine().trim());
		}

		while (in.hasNextLine()) {
			String[] row = in.nextLine().split(" ", 2);
			rows.add(new IndexRow(Integer.parseInt(row[0]), row[1].substring(1, row[1].length()-2)));
		}
		
		in.close();
	}
	
	public  String toString()
	{
		return this.name;
	}
}